<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ params.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportExcel"
          >导出</el-button>
          <el-button
            v-if="checkPermission('add-employee')"
            size="small"
            type="primary"
            @click="addEmployee"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="EmployeeList">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column
            prop=""
            label="姓名"
            sortable=""
            type="flex"
            justify="center"
          >
            <template #default="{ row }">
              <el-row type="flex" justify="center" class="avatarBox">
                <img
                  v-imgErr="require('@/assets/common/头像.jpg')"
                  :src="row.staffPhoto"
                  alt=""
                  class="avatar"
                  @click="ShowQRCode(row.staffPhoto)"
                >
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="employmentFormat"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="" label="入职时间" sortable="">
            <template #default="{ row }">{{
              row.correctionTime | formatDate
            }}</template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template #default="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployees(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="params.size"
            :total="params.total"
            :current-page="params.page"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工模态框 -->
      <add-employee
        :show-dialog.sync="showDialog"
        @addEmployee="update2lastPage"
      />
      <!-- 二维码模态框 -->
      <el-dialog
        title="头像"
        :visible="isShowQRCode"
        @close="isShowQRCode = false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色管理弹窗 -->
      <assignRole ref="assignRole" :user-id="userId" :show-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
// 导出接口
import { getEmployeeList, delEmployee } from '@/api/employee'
// 枚举数据
import employees from '@/api/constant/employees'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
// 角色管理弹窗
import assignRole from './components/assign-role.vue'
export default {
  components: { addEmployee, assignRole },
  data() {
    return {
      params: {
        // 页码
        page: 1,
        // 每页条数
        size: 5,
        // 总数
        total: 0
      },
      // 员工数据
      EmployeeList: [],
      showDialog: false,
      isShowQRCode: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 点击角色显示角色弹窗
    async showRole(id) {
      await this.$refs.assignRole.getUserDetailById(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 点击头像显示二维码
    ShowQRCode(url) {
      // 有传数据的话显示二维码
      if (url) {
        this.isShowQRCode = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url, {
            color: {
              dark: '#e35ef5', // Blue dots
              light: '#0000' // Transparent background
            }
          })
        })
      }
    },
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.params)
      console.log(rows)
      this.params.total = total
      // 因为本地数据服务器缺少了一个 enableState 属性
      // 这里对所有的员工进行处理, 如果没有这个值就补个1
      this.EmployeeList = rows.map((item) => ({
        ...item,
        enableState: item.enableState || 1
      }))
      // console.log(this.EmployeeList)
    },
    // 点击改变页码
    currentChange(val) {
      this.params.page = val
      this.getEmployeeList()
    },
    // 格式化聘用形式
    employmentFormat(row, col, cell, value) {
      const obj = employees.hireType.find(
        (item) => Number(item.id) === Number(cell)
      )
      // console.log(obj)
      //  避免obj没有的时候会报错
      return obj ? obj.value : '未知'
    },
    // 导出Excel
    async exportExcel() {
      // 发请求
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.params.total
      })
      console.log(rows)
      // 提示
      this.$message.success('操作成功')
      const dict = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // 遍历字典生成表头
      const header = Object.keys(dict)

      // 遍历数组 把数组的对象改造成数组
      const data = rows.map((obj) => {
        return this.obj2Arr(obj, dict)
      })
      // 调用导出库 按需引入
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header,
        data
      })
    },
    // 导出获取的数据 对象转化成数组
    obj2Arr(obj, dict) {
      // 根据字典排序 转化数组
      const newObj = []
      for (const key in dict) {
        // newKey =    timeOfEntry , mobile ,username ...
        const newKey = dict[key]
        // newVal =  obj[timeOfEntry]   =>  每一个属性值 "2018-11-02"
        const newVal = obj[newKey]
        if (newKey === 'formOfEmployment') {
          // 聘用形式处理
          const obj = employees.hireType.find((item) => item.id === newVal)
          // obj => {id:1,value:'正式'}
          newObj.push(obj ? obj.value : '未知')
        } else if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          // 时间格式处理
          newObj.push(formatDate(newVal))
        } else {
          newObj.push(newVal)
        }
      }
      // 返回数据
      return newObj
    },
    // 删除打工仔
    async delEmployees(id) {
      try {
        // 询问
        await this.$confirm('确定要删除嘛？')
        // 发请求
        await delEmployee(id)
        // 提示成功
        this.$message.success('操作成功')
        // 只剩一条数据返回上一页
        if (this.params.total > 1 && this.EmployeeList.length === 1) {
          this.params.page--
        }
        // 刷新数据
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    // 新增员工
    addEmployee() {
      this.showDialog = true
    },
    // 更新数据 跳到最后一页
    update2lastPage() {
      this.params.total++
      this.params.page = Math.ceil(this.params.total / this.params.size)
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.avatarBox {
  height: 80px;
}
.avatar {
  object-fit: contain;
}
</style>
